;
(function () {
  'use strict'

  var el_todo_list = document.querySelector('.todo_list');
  var el_search = document.querySelector('.search');
  var el_add = document.querySelector('.add');
  var todo_list;

  init();

  function init() {
    render();
    bind_submit();
  }

  function get_data(form) {
    var data = {};
    var input_list = form.querySelectorAll('input');
    for (var i = 0; i < input_list.length; i++) {
      var input = input_list[i];
      var key = input.name;
      var val = input.value;
      data[key] = val;
    };
    if (!val) return;
    return data;
  };

  function bind_search() {
    el_search.addEventListener('submit', function (event) {
      event.preventDefault();

      var el_search_result = get_data(el_todo_list);
      b.read(event);
      el_search_result.reset();
      render();
    });
  };

  function bind_submit() {
    el_add.addEventListener('submit', function (event) {
      event.preventDefault();

      var new_list_item = get_data(el_add);
      if (!new_list_item) return;
      b.add(new_list_item);
      el_add.reset();
      render();
    });
  };

  function render() {
    el_todo_list.innerHTML = '';
    todo_list = b.read();
    todo_list.forEach(function (list_item) {
      var el_list_item = document.createElement('div')
      el_list_item.innerHTML = `
      <div class="row">
      <div class="col col-8">
      <p>· ${list_item.content}</p>
      </div>
      <div class="col col-4 control">
      <button class="finish" data-id="${list_item.id}" id="${list_item.id}">Done</button>
      <button class="edit" data-id="${list_item.id}" id="${list_item.id}">Edit</button>
      <button class="delete" data-id="${list_item.id}" id="${list_item.id}">Delete</button>
      </div>
      </div>
      `;
      var delete_btn = el_list_item.querySelector('.delete');
      console.log('delete_btn:', delete_btn);
      delete_btn.addEventListener('click', function () {
        var id = parseInt(delete_btn.dataset.id);
        b.del(id);
        render();
      });

      el_todo_list.insertBefore(el_list_item, el_todo_list.firstChild);
    })
  }

})();